﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Alerts_Administration_2010.classes.views.Controls
{
    public class RadioButtonField : DataControlField
    {
        private RadioButtonList rblEventTypes;

        public string DataFieldValues { get; set; }
        public string DataField { get; set; }

        protected override DataControlField CreateField()
        {
            return new AlertEventTypeField();
        }

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
        {
            base.InitializeCell(cell, cellType, rowState, rowIndex);

            if (cellType == DataControlCellType.DataCell)
            {
                if (rowState == DataControlRowState.Edit)
                {
                    this.rblEventTypes = new RadioButtonList();
                    this.rblEventTypes.DataBinding += new EventHandler(rblEventTypes_DataBinding);
                    cell.Controls.Add(this.rblEventTypes);
                }
            }
        }

        private void rblEventTypes_DataBinding(object sender, EventArgs e)
        {
            Control container = ((Control)sender).NamingContainer;
            object dataItem = DataBinder.GetDataItem(container);
            Dictionary<string, string> values = DataBinder.GetPropertyValue(dataItem, DataFieldValues) as Dictionary<string, string>;
            string eventType = DataBinder.GetPropertyValue(dataItem, DataField) as string;

            foreach (KeyValuePair<string, string> pair in values)
            {
                this.rblEventTypes.Items.Add(
                    new ListItem(pair.Value, pair.Key)
                    {
                        Selected = eventType.Equals(pair.Key)
                    });
            }
        }

        public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
        {
            base.ExtractValuesFromCell(dictionary, cell, rowState, includeReadOnly);

            dictionary.Add(DataField, this.rblEventTypes.SelectedItem.Value);
        }
    }
}
